package com.xiaoxin.yixinai.wx;

import java.math.BigInteger;
import java.net.URLEncoder;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.xiaoxin.yixinai._frame.base.BaseRepository;
import com.xiaoxin.yixinai._frame.base.BaseServiceProxy;
import com.xiaoxin.yixinai._frame.utils.HttpHelper;
import com.xiaoxin.yixinai.activity.Activity;
import com.xiaoxin.yixinai.activity.ActivityService;
import com.xiaoxin.yixinai.activity.wxuser.WxUser;
import com.xiaoxin.yixinai.activity.wxuser.WxUserRepository;
import com.xiaoxin.yixinai.activity.wxuser.WxUserService;
import com.xiaoxin.yixinai.userinfo.UserInfo;

@Service
@Transactional
public class WxService extends BaseServiceProxy<UserInfo> {
 
	@Resource
	private WxUserService wxUserService;
	
	@Resource
	private ActivityService activityService;
	
	@Resource
	private EntityManager entityManager;
	
	@Override
	protected BaseRepository<UserInfo> getBaseRepository() {
		return null;
	}
	
	public String getAuthorizeURL(String appid, String url, String scope) {
		StringBuffer sb = new StringBuffer()
			.append("https://open.weixin.qq.com/connect/oauth2/authorize?")
			.append("appid=").append(appid).append("&redirect_uri=").append(URLEncoder.encode(url))
			.append("&response_type=code&scope=").append(scope)
			.append("&state=").append(UUID.randomUUID()).append("#wechat_redirect");
		return sb.toString();
	}
	
	public WxUser doAuthorizeAction(String appId,String secret,String code,Integer activityId,Integer parentId) {
		StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?")
			.append("appid=").append(appId).append("&secret=").append(secret)
			.append("&code=").append(code).append("&grant_type=authorization_code");
		
		String ret = HttpHelper.textGet(url.toString());
		Map<String,Object> token = new Gson().fromJson(ret, Map.class);
		if(token == null || token.get("openid") == null || token.get("access_token") == null)
			return null;
		
		String openid = (String)token.get("openid");
		WxUser user = wxUserService.findByActivityIdAndOpenid(activityId,openid);
		if(user == null) {
			user = new WxUser();
			user.setActivityId(activityId);
			user.setOpenid(openid);
			user.setParentId(parentId);
			user.setViewNum(0);
			user.setForwardNum(0);
			if(parentId==null || parentId==0) {//一级推广员
				Activity activity = activityService.findOne(activityId);
				user.setCompanyId(activity.getCompanyId());
				user.setGrade(1);
			}else {
				WxUser parentUser = wxUserService.findOne(parentId);
				user.setCompanyId(parentUser.getCompanyId());
				user.setGrade(parentUser.getGrade()+1);
				parentUser.setViewNum(parentUser.getViewNum()+1);
				parentUser.setViewLastTime(new Date(System.currentTimeMillis()));
			}
		}
		String access_token = (String)token.get("access_token");
		StringBuffer url2 = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?access_token=")
			.append(access_token).append("&lang=zh_CN&openid=").append(openid);
			
		String ret2 = HttpHelper.textGet( url2.toString() );
		Map<String,Object> wxUser = new Gson().fromJson(ret2, Map.class);

		String nickname=(String)wxUser.get("nickname");
		if(hasEmoji(nickname)){
			nickname = replaceEmoji(nickname);
		}
		user.setNickName(nickname);
		user.setHeadimgurl((String)wxUser.get("headimgurl"));
		user.setSex(((Double)wxUser.get("sex")).intValue());
		user.setLanguage((String)wxUser.get("language"));
		user.setCity((String)wxUser.get("city"));
		user.setProvince((String)wxUser.get("province"));
		user.setCountry((String)wxUser.get("country"));
		
		wxUserService.save(user);
		
		return user ;				
	}
	
//	public WxUser doAuthorizeAction(String appId,String secret,String code) {
//		StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?")
//			.append("appid=").append(appId).append("&secret=").append(secret)
//			.append("&code=").append(code).append("&grant_type=authorization_code");
//		
//		String ret = HttpHelper.textGet(url.toString());
//		Map<String,Object> token = new Gson().fromJson(ret, Map.class);
//		if(token == null || token.get("openid") == null || token.get("access_token") == null)
//			return null;
//		
//		String openid = (String)token.get("openid");
//		WxUser user = wxUserService.findByAppIdAndOpenId(appId,openid);
//		String access_token = (String)token.get("access_token");
//		if(user == null) {
//			user = new WxUser();
//			user.setAppId(appId);
//			user.setOpenId(openid);
//		}
//			
//		StringBuffer url2 = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?access_token=")
//			.append(access_token).append("&lang=zh_CN&openid=").append(openid);
//			
//		String ret2 = HttpHelper.textGet( url2.toString() );
//		Map<String,Object> wxUser = new Gson().fromJson(ret2, Map.class);
//
//		String nickname=(String)wxUser.get("nickname");
//		if(hasEmoji(nickname)){
//			nickname = replaceEmoji(nickname);
//		}
//		user.setNickName(nickname);
//		user.setHeadImg((String)wxUser.get("headimgurl"));
//		
//		wxUserService.save(user);
//		return user ;				
//	}
	
	    /** 
	    * @Title:判断是否存在特殊字符串 
	     */  
	    private boolean hasEmoji(String content){  
	        Pattern pattern = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]");  
	        Matcher matcher = pattern.matcher(content);  
	        if(matcher .find()){  
	            return true;      
	        }  
	            return false;  
	    }  
	    
	    /** 
	     * @Title:替换字符串中的emoji字符 
	      */  
	     private String replaceEmoji(String str){  
	         if(!hasEmoji(str)){  
	             return str;  
	         }else{  
	             str=str.replaceAll("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", " ");  
	             return str;  
	         }  
	           
	     }  
	     
	    
}
